package com.mjk.manager.api.config;

import com.mjk.common.core.jdbc.service.plus.idbservice.BeeDBService;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeQueryWrapper;
import com.mjk.common.tools.springextend.BeeApplicationListener;
import com.mjk.common.web.getway.restful.prototal.ws.soap.config.BeeSoapConfig;
import com.mjk.manager.api.apipost.IApiPostPush;
import com.mjk.manager.api.apipost.impl.DefaultApiPostPushImpl;
import com.mjk.manager.api.model.ApiModel;
import com.mjk.manager.gen.dto.GenDto;
import com.mjk.manager.gen.work.GenWork;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

@Configuration
public class ApiConfig extends BeeSoapConfig implements BeeApplicationListener {
	
    @Bean
    @ConditionalOnMissingBean
    public IApiPostPush defaultApiPostPush() {
        return new DefaultApiPostPushImpl();
    }	    
	@Override
	public void doApplicationEvent(ContextRefreshedEvent event) {
		BeeDBService beeDBService = event.getApplicationContext().getBean(BeeDBService.class);
		//获取配置的api接口信息
		BeeQueryWrapper wrapper = new BeeQueryWrapper(new ApiModel());
		wrapper.eq(ApiModel::getIsDynamic,"1");
        List<ApiModel> models = beeDBService.findManyByWrapper(wrapper);
		if(CollectionUtils.isEmpty(models)){
			return;
		}
		Map<String,List<ApiModel>> maps =  models.stream().filter(item->"1".equals(item.getApiType())).collect(Collectors.groupingBy(ApiModel::getApiWork));
		GenWork gen = event.getApplicationContext().getBean(GenWork.class);
		
		for(Entry<String,List<ApiModel>> entry : maps.entrySet()){
			gen.publish(new GenDto(entry.getValue().get(0),entry.getValue()));
		}
		//对于webservice接口
		List<ApiModel> wsModels =  models.stream().filter(item->"2".equals(item.getApiType())).toList();
		for(ApiModel model : wsModels) {
			gen.publish(new GenDto(model));
		}
	}
	
	
	@Override
	public int getOrder() {		
		return 2;
	}
}
